package cn.edu.ncut.cs.springboot.springbootdatabase.Controller;

import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Account;
import cn.edu.ncut.cs.springboot.springbootdatabase.entity.PrisonGuard;
import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Prisoner;
import cn.edu.ncut.cs.springboot.springbootdatabase.service.AccountService;
import cn.edu.ncut.cs.springboot.springbootdatabase.service.PrisonGuardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/prisonGuard")
public class PrisonGuardController {
    @Autowired
    private PrisonGuardService prisonGuardService;
    @Autowired
    private AccountService accountService;
    @GetMapping
    public List<PrisonGuard> listUser() {
        return prisonGuardService.findAll();
    }

    @GetMapping("/{id}")
    public Optional<PrisonGuard> findById(@PathVariable("id") Integer id){
        return prisonGuardService.findById(id);
    }
    @PostMapping("/add")
    public String add(@RequestBody() PrisonGuard prisonGuard){
        try {
            // 保存Prisoner信息到prisoner表
            prisonGuard.encodePassword();
            prisonGuardService.savePrisonGuard(prisonGuard);
            Account account = new Account();
            account.setRegisterTime(LocalDateTime.now());
            account.setRole("PrisonGuard");
            account.setId((prisonGuard.getId()));
            account.setUsername(prisonGuard.getName());
            account.setPassword(prisonGuard.getPassword());
            account.encodePassword();
            // 保存Account信息到account表
            accountService.saveAccount(account);
            return String.valueOf(new ResponseEntity<>("success!", HttpStatus.OK));
        } catch (Exception e) {
            return String.valueOf(new ResponseEntity<>("添加过程出现异常，请检查输入数据及相关配置", HttpStatus.INTERNAL_SERVER_ERROR));
        }
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") Integer id){
        Optional<PrisonGuard> prisonGuard = prisonGuardService.findById(id);
        if (prisonGuard.isPresent()) {
            // 获取prisoner的name并调用accountService的新方法删除对应的Account对象
            accountService.deleteUsername(prisonGuard.get().getName());
            prisonGuardService.deletePrisonGuard(id);
            return "success!";
        }
        return "未找到对应的囚犯信息，删除失败";
    }
}
